/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.martinimix.beans.bind;

import java.lang.reflect.Field;

import net.martinimix.attribute.BusinessObjectProperty;

import org.apache.commons.attributes.Attributes;

/**
 * Provides a {@link BusinessObjectProperty} attribute aware field property mapping handler.
 * 
 * @author Scott Rossillo
 *
 */
public final class AttributeAwareFieldPropertyMappingHandler extends SimpleFieldPropertyMappingHandler {

	/**
	 * Creates a new attribute aware field property mapping handler.
	 */
	public AttributeAwareFieldPropertyMappingHandler() {
		super();
	}
	
	/**
	 * Provides property names based on {@link BusinessObjectProperty} attributes.  If a
	 * <code>BusinessObjectProperty</code> is not for the field this method relies on the
	 * super class to provide a mapping.
	 * 
	 * @see net.martinimix.beans.bind.FieldPropertyMapper#findPropertyName(java.lang.Class, java.lang.String)
	 */
	protected String findPropertyName(Class clazz, String field) {
		
		BusinessObjectProperty boProp = findProperty(clazz, field);
		
		return boProp != null ? boProp.getFullyQualifiedName() : super.findPropertyName(clazz, field);
	}
	
	/**
	 * Finds the business object property associated with the given class and field.
	 * 
	 * @param clazz the bean <code>Class</code> whose <code>BusinessObjectProperty</code> 
	 * will be returned
	 * 
	 * @param fieldName the field whose <code>BusinessObjectProperty</code> will be returned
	 * 
	 * @return the <code>BusinessObjectProperty</code> associated with the given
	 * <code>clazz</code> and <code>fieldName</code> if assigned; <code>null</code> otherwise
	 */
	protected final BusinessObjectProperty findProperty(Class clazz, String fieldName) {
		
		Field field = null;
		BusinessObjectProperty boProp = null;
		
		try {
			field = clazz.getDeclaredField(fieldName);
			boProp = (BusinessObjectProperty) Attributes.getAttribute(field, BusinessObjectProperty.class);
		} catch (SecurityException e) {
			throw new BusinessObjectBindException(
					"Field [" + fieldName + "] not accessible, check your security manager settings!");
		} catch (NoSuchFieldException e) {
			Class superClass = clazz.getSuperclass();
			if(superClass != null && !superClass.equals(Object.class)) {
				return findProperty(superClass, fieldName);
			}
		}
				
		return boProp;
	}

}
